package com.albert.tool;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.util.Map;

public class JsonUtils {

    private static final ObjectMapper mapper = new ObjectMapper();
    // 模型转字典
    public static Map<String, Object> objectToMap(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Boolean.class, new BooleanToIntSerializer());
        module.addSerializer(boolean.class, new BooleanToIntSerializer());
        mapper.registerModule(module);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.convertValue(obj, Map.class);
    }

    // 字典转JSONString
    public static String mapToJSonStr(Map<Object, Object> map) {
        // 创建 Jackson 的 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Boolean.class, new BooleanToIntSerializer());
        module.addSerializer(boolean.class, new BooleanToIntSerializer());
        mapper.registerModule(module);
        String jsonStr = "";
        try {
            jsonStr = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        // 转换为 JSON 字符串
        return jsonStr;
    }

    // 模型转JSONString
    public static String objectToJSonStr(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Boolean.class, new BooleanToIntSerializer());
        module.addSerializer(boolean.class, new BooleanToIntSerializer());
        mapper.registerModule(module);
        // 模型转 JSON 字符串
        String jsonString = null;
        try {
            jsonString = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonString;
    }

    /**
     * 判断是否是合法 JSON 字符串
     */
    public static boolean isJsonString(String str) {
        if (str == null || str.isEmpty()) return false;
        try {
            // 尝试解析成 Object（Map 或 List 都可以）
            mapper.readTree(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 将 JSON 字符串转换为指定模型
     */
    public static <T> T fromJson(String jsonString, Class<T> clazz) throws Exception {
        if (!isJsonString(jsonString)) {
            throw new IllegalArgumentException("不是合法的 JSON 字符串");
        }
        return mapper.readValue(jsonString, clazz);
    }
}

